package com.cyy.common.config.mybatisplus;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.Objects;


@Configuration
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Integer userId = StpUtil.getLoginIdDefaultNull() == null ? null : Integer.valueOf((String) StpUtil.getLoginId());

        Object createTime = this.getFieldValByName("createTime", metaObject);
        if (Objects.isNull(createTime)) {
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        }
        this.strictInsertFill(metaObject, "updateBy", Integer.class, userId);

        Object updateTime = this.getFieldValByName("updateTime", metaObject);
        if (Objects.isNull(updateTime)) {
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }
        this.strictInsertFill(metaObject, "updateBy", Integer.class, userId);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Integer userId = StpUtil.getLoginIdDefaultNull() == null ? null : Integer.valueOf((String) StpUtil.getLoginId());
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, "updateBy", Integer.class, userId);
    }
}
